<template>
	<div ref="chartRef" class="w-full h-full"></div>
</template>

<script setup lang="ts">
import { tryOnUnmounted, useDebounceFn } from '@vueuse/core';
import * as echarts from 'echarts';
import { useEventListener } from '/@/hooks/event/useEventListener';
interface ItemType {
	key: string;
	val: number;
}
const props = defineProps({
	data: {
		type: Array<ItemType>,
		default: () => [],
	},
});
const chartRef = ref();
let resizeFn = resize;
let removeResizeFn = () => {};
let instance: any;
const chartData = reactive<{ selectTime: string[]; deviceCount: number[] }>({
	selectTime: [],
	deviceCount: [],
});
resizeFn = useDebounceFn(resize, 200);
watch(
	() => props.data,
	() => {
		getChartData();
		setOptions();
	},
	{
		deep: true,
	}
);
const getChartData = () => {
	chartData.selectTime = [];
	chartData.deviceCount = [];
	for (let i = 0; i < props.data?.length; i++) {
		const d: ItemType = props.data[i];
		chartData.selectTime.push(d.key);
		chartData.deviceCount.push(d.val);
	}
};
const setOptions = () => {
	getChartData();
	const options = {
		color: '#c23531',
		tooltip: {
			trigger: 'axis',
		},
		xAxis: {
			type: 'category',
			axisLine: {
				lineStyle: {
					color: '#fff',
				},
			},
			data: chartData.selectTime,
		},
		yAxis: {
			type: 'value',
			axisLine: {
				lineStyle: {
					color: '#fff',
				},
			},
			minInterval: 1, //最小刻度是1
		},
		grid: {
			borderWidth: 0,
			top: 10,
			bottom: 4,
			left: 4,
			right: 0,
			textStyle: {
				color: '#fff',
			},
			containLabel: true,
		},
		series: [
			{
				data: chartData.deviceCount,
				type: 'line',
				smooth: true,
			},
		],
	};
	instance && instance.clear();
	!instance && (instance = echarts.init(chartRef.value));
	instance.setOption(options);
};
function resize() {
	const config = {
		animation: {
			duration: 300,
			easing: 'quadraticIn',
		},
	};
	instance.resize(config);
}
onMounted(() => {
	setOptions();
	const { removeEvent } = useEventListener({
		el: window,
		name: 'resize',
		listener: resizeFn,
	});
	removeResizeFn = removeEvent;
});

tryOnUnmounted(() => {
	removeResizeFn();
});
</script>
